#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define M 8
#define N 10

int A[M][N]=
  {

    {1,2,27,4,57,6,99,8,98,10},
	{2,69,4,53,6,7,8,9,10,11},
	{8,4,6,2,7,40,7,80,12,15},
	{10,23,45,7,89,10,13,9,18,20},
	{43,8,12,9,23,6,8,11,17,30},
	{9,5,1,72,56,7,5,19,6,8},
	{10,45,7,2,8,25,6,8,2,13},
	{10,55,30,29,5,8,6,2,5,20},
  };

int B[M][N]={0};
int C[M][N]={0};

int minOf3(int a,int b,int c)
{
	if(a<=b && a<=c)
		return a;
	else if(b<=c)
		return b;
	else
		return c;
}

int getMin(int i,int j)
{
	int a1,a2,a3;
	if(j-1>=0)
		a1=B[i-1][j-1];
	else
		a1=INT_MAX;
	a2=B[i-1][j];
	if(j+1<N)
		a3=B[i-1][j+1];
	else
		a3=INT_MAX;
	int min=minOf3(a1,a2,a3);
	if(min==a1)
		C[i][j]=-1;
	else if(min==a2)
		C[i][j]=0;
	else
		C[i][j]=1;
	return min;
}

void dp()
{
	for(int i=0;i<M;i++)
	{
		for(int j=0;j<N;j++)
		{
			B[i][j]=A[i][j];
		}
	}
	for(int i=1;i<M;i++)
	{
		for(int j=0;j<N;j++)
		{
			B[i][j]+=getMin(i,j);
		}
	}
}

void printB()
{
	for(int i=0;i<M;i++)
	{
		for(int j=0;j<N;j++)
		{
			printf("%4d ",B[i][j]);
		}
		printf("\n");
	}
}

void printA()
{
	for(int i=0;i<M;i++)
	{
		for(int j=0;j<N;j++)
		{
			printf("%4d ",A[i][j]);
		}
		printf("\n");
	}
}

void printTrace(int startCol)
{
	printf("col%d:%d ",startCol+1,A[M-1][startCol]);
	int j=startCol+C[M-1][startCol];
	for(int i=M-2;i>=0;i--)
	{
		printf("col%d:%d ",j+1,A[i][j]);
		j=C[i][j]+j;
	}
	printf("\n");
}

int getResult()
{
	int min=INT_MAX,mini;
	for(int i=0;i<N;i++)
	{
		if(B[M-1][i]<min)
		{
			min=B[M-1][i];
			mini=i;
		}

	}
	printf("min cost:%d\n",min);
	return mini;
}

int main()
{
	dp();
	printB();
	printf("\n");
	printA();
	int scol=getResult();
	printTrace(scol);
	//getchar();
}

